from django.db import models
from django.contrib.auth.models import AbstractUser
from itsdangerous import TimedJSONWebSignatureSerializer as TGWSSerializer

from django.conf import settings

from meiduo.utils.models import BaseModel
from users import constants


# 创建User模型类
class User(AbstractUser):
    '''创建User模型类'''
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    # 增加邮箱验证字段
    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')
    # 增加默认地址字段
    default_address = models.ForeignKey('Address', related_name='users', null=True, blank=True,
                                        on_delete=models.SET_NULL, verbose_name='默认地址')

    # 设置表名
    class Meta:
        db_table = 'tb_user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    # 获取验证连接地址
    def generate_verify_email_url(self):
        # 创建TimedJSONWebSignatureSerializer 一个对象,
        serializer = TGWSSerializer(secret_key=settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)

        data = {'id': self.id, 'email': self.email}

        # 在连接中对用户的信息进行加密
        token = serializer.dumps(data).decode()
        # 生成url
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token

        return verify_url

    # 验证邮件连接
    @staticmethod
    def check_verify_email_url(token):
        # 创建TimedJSONWebSignatureSerializer 一个对象
        serializer = TGWSSerializer(secret_key=settings.SECRET_KEY)
        # 解密
        try:
            res = serializer.loads(token)
        except BaseException:
            return None

        id = res.get('id')
        email = res.get('email')

        # 查询用户
        try:
            user = User.objects.get(id=id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


# 用户地址管理模型类
class Address(BaseModel):
    """
    用户地址
    """
    # 地址所属的用户
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
    # 地址的标题
    title = models.CharField(max_length=20, verbose_name='地址名称')
    receiver = models.CharField(max_length=20, verbose_name='收货人')
    province = models.ForeignKey('areas.Area', related_name='province_address', on_delete=models.PROTECT,
                                 verbose_name='省')
    city = models.ForeignKey('areas.Area', related_name='city_address', on_delete=models.PROTECT, verbose_name='市')
    district = models.ForeignKey('areas.Area', related_name='district_address', on_delete=models.PROTECT,
                                 verbose_name='区')
    # 详细地址
    place = models.CharField(max_length=50, verbose_name='地址')
    mobile = models.CharField(max_length=11, verbose_name='手机')
    tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
    email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱')
    is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_address'
        verbose_name = '用户地址'
        verbose_name_plural = verbose_name
        ordering = ['-update_time']
